﻿using System;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SapaFinance.GenericRepository;

namespace SapaFinance.UI
{
    public class MvcApplication : HttpApplication
    {
      //  private ITransaction _transact;
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
            //routes.MapRoute(
            // null, // Route name
            // "{controller}/{action}/{id}?Grid-mode={method}", // URL with parameters
            // new { controller = "Home", action = "Index", id = UrlParameter.Optional, mode = "[A-Za-z.-]" } // Parameter defaults
            // );
        }

        protected void Application_Start()
        {
            //our setup
            IOC.Build();
          
          
           
            //mvc stuff
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }


        protected void Application_BeginRequest()
        {
        }

        protected void Application_EndRequest()
        {
        }
     

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Response.Clear();
            //   string action = "General";

            var httpException = exception as HttpException;
            if (httpException != null)
            {

                string action;
                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // page not found
                        action = "HttpError404";
                        break;
                    case 500:
                        // server error
                        action = "HttpError500";
                        break;
                    default:
                        action = "General";
                        break;
                }

                Redirect(exception.Message, action);
            }

            var dbEx = exception as DbEntityValidationException;
            if (dbEx != null){
                var validationErrors = dbEx.EntityValidationErrors.First();
                if (validationErrors != null){
                    var validationError = validationErrors.ValidationErrors.First();

                    Redirect(validationError.ErrorMessage, "General");
                }



            }

        }

        private void Redirect(string exception, string action)
        {
            // clear error on server
            Server.ClearError();
            //  Session.Add("Error", exception.StackTrace);
            Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception));
        }

        public void Application_End()
        {
            IOC.Dispose();
        }
    }
}